"use strict";
const passwordHash = require('yi-password-hash');
const ObjectID = require('mongodb').ObjectID;

const middleware = (req, res, next) => {

    req.redis.get('token:' + req.body.token, (e, user) => {
        if (e || !user) {
            return res.reply({code: 60005, message: "鉴权已过期，请重新授权登录"});
        }
        user = JSON.parse(user);

        user._id = new ObjectID(user._id);
        let userId = user._id;
        req.mongo.collection('store').find({
            _id: req.params.id,
            $or: [{userId: userId}, {members: userId}]
        }).next((e2, r2) => {
            if (e2 || !r2) {
                return res.reply({code: 10002, message: "该账号未注册该店铺！"});
            }
            user.store = r2;
            user.store.userId = user.store.userId || '';
            if (user.store.userId.toString() === userId.toString())
                user.role = 'storeManager';
            else
                user.role = 'storeMember';

            req.mongo.collection('role').find({_id: user.role})
                .limit(1)
                .next(function (err, role) {
                    if (err) return res.err.mongoError();
                    if (!role) return res.reply({code: 60007, message: "未找到对应的角色"});
                    user.roleName = role.name;
                    user.apis = role.apis;
                    user.menus = role.menus;

                    req.redis.set('token:' + req.body.token, JSON.stringify(user), (e0, r0) => {
                        res.reply({code: 0, message: "登录店铺成功", data: user});

                        if(req.body.qrId){
                            req.redis.client.ttl('QrCodeStoreLogin:' + req.body.qrId,(e5,r5)=>{
                                if(r5>0){
                                    req.redis.setValueAndExpire('QrCodeStoreLogin:' + req.body.qrId,JSON.stringify(user),r5,(e4,r4)=>{

                                    });
                                }
                            });
                        }
                    });
                });
        });

    });
};

module.exports = {
    open: true,
    description: '店铺登录',
    middleware: middleware,
    handler(req, res, next) {

    }
};
